import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { Clipboard } from '@angular/cdk/clipboard';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FinanceDrawbackService } from './finance-drawback.service';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-finance-drawback',
  templateUrl: './finance-drawback.component.html',
  styleUrls: ['./finance-drawback.component.scss'],
  providers: [DatePipe]
})
export class FinanceDrawbackComponent implements OnInit {
  @ViewChild('flowRecord', { static: false }) flowRecord: any;

  seachParams: any = {
    state: '', // 0 待审核 1.已打款 2.审核不通过 3.待打款
    createTime: '',
    endTime: ''
  };
  dateArrs: Date[] = [];

  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  tableData: any = [];

  // 审核 && 打款 Modal
  isAdoptPaymentVisible: boolean = false;
  modalTitle: string = '';
  
  adoptLoading: boolean = false;
  adoptNotLoading: boolean = false;
  paymentLoading: boolean = false;
  auditDesc: string = ''; // 审核 | 打款 备注

  operationItem: any = {};

  constructor(
    private clipboard: Clipboard,
    private message: NzMessageService,
    private datePipe: DatePipe,
    private services: FinanceDrawbackService,
    private router: Router
  ) { }

  ngOnInit(): void {
    this.loadTable();
  }

  async loadTable() {
    try {
      let params = {
        ...this.seachParams,
        page: this.tableParams.page,
        pageSize: this.tableParams.pageSize
      }
      this.tableParams.tableLoading = true;
      const res: any = await this.services.getDrwabackList(params);
      this.tableParams.tableLoading = false;

      if (res.code == 0) {
        const { records, total }: any = res.data;
        this.tableData = records;
        this.tableParams.total = total;
      }
    } catch (error: any) {
      this.tableParams.tableLoading = false;
      this.tableData = [];
      this.tableParams.total = 0;
      this.message.error(error);
    }
  }

  // date change
  timeChange(result: any) {
    this.seachParams.createTime = result.length ? this.datePipe.transform(new Date(result[0]), 'yyyy-MM-dd') : '';
    this.seachParams.endTime = result.length ? this.datePipe.transform(new Date(result[1]), 'yyyy-MM-dd') : '';
  }

  seachData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    Object.keys(this.seachParams).forEach((key: any) => {
      this.seachParams[key] = '';
    })
    this.dateArrs = [];

    this.tableParams.page = 1;
    this.loadTable();
  }

  // 流水记录
  openRecord(item: any) {
    this.operationItem = item;
    this.flowRecord.isRecordVisible = true;
  }

  jumpPage(item: any) {
    this.router.navigate(['/finance/drawback-detail'], {
      queryParams: {
        id: item.id
      }
    })
  }

  // 下载
  downFile(item: any) {
    window.open(item.icon, 'blank');
  }

  // 复制信息
  copyInfo(item: any) {
    this.clipboard.copy(`账户名称：${ item.bankName } 银行账号：${ item.bankAccount } 开户行：${ item.bankAddress }`);
    this.message.success('已经成功复制到剪切板');
  }

  /**
   * open modal
   * @param num 0：审核，1：打款 
   */
  openModal(num: number, item: any) {
    this.loadingFalse();

    this.operationItem = item;
    this.modalTitle = num == 0 ? '审核' : '打款';
    this.auditDesc = '';
    this.isAdoptPaymentVisible = true;
  }
  handleCancel() {
    this.isAdoptPaymentVisible = false;
  }

  /**
   * 审核 | 打款
   * @param state 1：审核通过，2：审核不通过，3：打款
   */
  async subAdoptPayment(state: number) {
    try {
      let params = {
        id: this.operationItem.id,
        auditDesc: this.auditDesc,
        state: state
      }
      if (state == 2 && !this.auditDesc) {
        this.message.warning('请先输入备注');
        return
      }
      switch (state) {
        case 1:
          this.paymentLoading = true;
          break
        case 2:
          this.adoptNotLoading = true;
          break
        case 3:
          this.adoptLoading = true;
          break
      }

      const res: any = await this.services.drawbackExaminePayment(params);
      this.loadingFalse();

      if (res.code == 0) {
        this.message.success('操作成功');
        this.isAdoptPaymentVisible = false;
        this.loadTable();
      } else {
        this.message.error(res.message || '操作失败');
      }
    } catch (error: any) {
      this.loadingFalse();
      this.message.error(error);
    }
  }

  loadingFalse() {
    this.paymentLoading = false;
    this.adoptLoading = false;
    this.adoptNotLoading = false;
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }
}
